#!/usr/bin/python -u
#!/usr/bin/env python -u

import sys
import tos

from message import DataMessage,  AM_TYPE as AM_DATAMESSAGE
from alarm   import AlarmMessage, AM_TYPE as AM_ALARMMESSAGE

if '-h' in sys.argv or len(sys.argv) < 2:
    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:115200"
    sys.exit()
    
if '-a' in sys.argv:
	print_all = True
else:
	print_all = False

am = tos.AM()

while True:
	p = am.read()
	if print_all:
		print "Message from ", p.source, " to ", p.destination
	if p and (p.destination == 0 or p.destination == 65535 or print_all):
		if p.type == AM_DATAMESSAGE:
			# This is a bit of a hack: am.read returns data as
			# a list of bytes, but DataMessage expects a string.
			# Maybe, we should consider using tos.message.MoteIF.
			msg = DataMessage(''.join([chr(i) for i in p.data]))
			# Beware! print is buffered, we use python -u to work around.
			print msg.get_time(), msg.get_voltage(), msg.get_temperature(), msg.get_humidity(), msg.get_lightPar(), msg.get_lightTsr()
			#print msg.get_source(), msg.get_voltage()
		elif p.type == AM_ALARMMESSAGE:
			msg = AlarmMessage(''.join([chr(i) for i in p.data]))
			print '# alarm', msg.get_source(), msg.get_object_node_id(), msg.get_content_type(), msg.get_time();
